package create;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * ClassName: Pool
 * Package: create
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-13
 * Time: 22:16
 */

//创建线程池
public class Pool {
    public static void main(String[] args) {

        //1.提供制定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor executor = (ThreadPoolExecutor) service;

        executor.setMaximumPoolSize(50); //设置线程池中线程数的上线

        //2.执行制定的线程的操作 需要提供实现Runnable或者Callable接口实例
        executor.execute(new NumberThread());
        executor.execute(new NumberThread1());

        try {
            Future future = service.submit(new NumberThread2());
            System.out.println("总和为: " + future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //关闭连接池
        service.shutdown();
    }
}

class NumberThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

class NumberThread1 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

class NumberThread2 implements Callable {
    @Override
    public Object call() throws Exception {
        int evenSum = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                evenSum += i;
            }
        }
        return evenSum;
    }
}